//
//  MONoticeSendViewController.m
//  MobileOffice
//
//  Created by 冰冰 on 2019/6/7.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MONoticeSendViewController.h"
#import "MONoticeSendViewCell.h"

@interface MONoticeSendViewController ()<UITableViewDelegate,UITableViewDataSource,XLsn0wPickerTimerDelegate>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataSource;

//选择的数据
@property(nonatomic,strong)NSMutableArray *selectedNameArray;
@property(nonatomic,strong)NSMutableArray *selectedIdArray;

@property(nonatomic,strong)UIView *headerView;
//发送 取消
@property(nonatomic,strong)UIView *bottomView;
//选择时间
@property(nonatomic,strong)UIButton *selectedDateButton;
//选择的时间
@property(nonatomic,copy)NSString *dateStr;
//意见
@property(nonatomic,strong)SNTextView *textView;
//送领导审核
@property(nonatomic,strong)UILabel *valueLabel;
//第一条数
@property(nonatomic,strong)NSArray *firstListData;


@end

@implementation MONoticeSendViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self creatView];

    [self initData];
    
}

-(void)creatView
{
    self.title = @"公文发送";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.tableHeaderView = self.headerView;
    
    [self.view addSubview:self.bottomView];
}

-(void)initData
{
    self.dataSource = [NSMutableArray array];
    self.selectedNameArray = [NSMutableArray array];
    self.selectedIdArray = [NSMutableArray array];
    
    NSString *url = [NSString stringWithFormat:@"%@/%@?authorization=%@",ODPSDB_ODPSDBQUERYSENDFLOWPATHV2_URL,self.waitModel.key,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    
    [PPNetworkHelper GET:url parameters:@{} success:^(id responseObject) {
        NSLog(@"获取发送路径：%@",responseObject);
        if ([responseObject[@"status"] integerValue]==1) {
            NSArray *arr = responseObject[@"dept"];
            for (int i = 0; i<arr.count; i++) {
                [self.selectedNameArray addObject:arr[i][@"nexttachename"]];
                [self.selectedIdArray addObject:arr[i][@"index"]];
            }
            self.valueLabel.text = arr[0][@"nexttachename"];
            NSArray *arr1 = responseObject[@"list"];
            self.firstListData = arr1;
            for (int i = 0; i<arr1.count; i++) {
                MONoticeSendModel *model = [[MONoticeSendModel alloc]init];
                model.nameStr = arr1[i];
                [self.dataSource addObject:model];
            }
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        NSLog(@"获取发送路径：%@",[error localizedDescription]);
    }];
    
}

#pragma mark -- 获取待办公文发送获取接收列表
-(void)getListDataForIndex:(NSString *)index tag:(NSInteger)tag
{
    if (tag==0) {
        self.dataSource = [NSMutableArray array];
        for (int i = 0; i<self.firstListData.count; i++) {
            MONoticeSendModel *model = [[MONoticeSendModel alloc]init];
            model.nameStr = self.firstListData[i];
            [self.dataSource addObject:model];
        }
        [self.tableView reloadData];
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"%@/%@/%@?authorization=%@",ODPSDB_ODPSDBQUERYSENDFLOWACTLISTV2_URL,self.waitModel.key,index,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
    
    [PPNetworkHelper GET:url parameters:@{} success:^(id responseObject) {
        NSLog(@"获取待办公文发送获取接收列表：%@",responseObject);
        if ([responseObject[@"status"] integerValue]==1) {
            self.dataSource = [NSMutableArray array];
            NSArray *arr1 = responseObject[@"list"];
            for (int i = 0; i<arr1.count; i++) {
                MONoticeSendModel *model = [[MONoticeSendModel alloc]init];
                model.nameStr = arr1[i];
                [self.dataSource addObject:model];
            }
            [self.tableView reloadData];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"获取待办公文发送获取接收列表：%@",[error localizedDescription]);
    }];
}


#pragma mark -- 发送 取消
-(void)clickSendOrCancelButton:(UIButton *)sender
{

    if (sender.tag==0) {
        
        if (self.textView.text.length==0) {
            [[ADShowMessage shareShowMessage]showTextOnly:@"先填写附加信息" showInView:self.view];
            return;
        }
        if (self.dateStr.length==0) {
            [[ADShowMessage shareShowMessage]showTextOnly:@"先选择时间" showInView:self.view];
            return;
        }
        if (self.textView.text.length==0) {
            [[ADShowMessage shareShowMessage]showTextOnly:@"先填写附加信息" showInView:self.view];
            return;
        }
        
        NSMutableArray *strArray = [NSMutableArray array];
        for (int i = 0; i<self.dataSource.count; i++) {
            MONoticeSendModel *model = self.dataSource[i];
            if ([model.selectedTypeStr integerValue]==1) {
                [strArray addObject:model.nameStr];
            }
        }
        if (strArray.count==0) {
            [[ADShowMessage shareShowMessage]showTextOnly:@"先选择接收人" showInView:self.view];
            return;
        }
        
        NSString *url = [NSString stringWithFormat:@"%@?authorization=%@",ODPSDB_ODPSDBSEND_URL,[NSString URLEncodedString:[MOUser sharedMOUser].token]];
        
        NSDictionary *par = @{
                              @"wjKey":self.waitModel.key,
                              @"yj":self.textView.text,//意见
                              @"toadr":[strArray componentsJoinedByString:@","],//接受人字符串 多个以“，”分隔
                              @"xbsj":self.dateStr//格式：yyyy/mm/dd
                              };
        [PPNetworkHelper POST:url parameters:par success:^(id responseObject) {
            NSLog(@"待办公文发送：%@",responseObject);
            if ([responseObject[@"status"] integerValue]==1) {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"officeTextStatusChange" object:nil];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            [[ADShowMessage shareShowMessage]showTextOnly:responseObject[@"msg"] showInView:self.view];
        } failure:^(NSError *error) {
            NSLog(@"待办公文发送：%@",[error localizedDescription]);
            [[ADShowMessage shareShowMessage]showTextOnly:[error localizedDescription] showInView:self.view];
        }];
        
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark -- 选择领导审核
-(void)clickSendSelectedButton:(UIButton *)sender
{
    [self.textView resignFirstResponder];
    
    SNXYSelectedNumberView *pickview = [[SNXYSelectedNumberView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    pickview.numberArray = [NSArray arrayWithArray:self.selectedNameArray];
    
    __weak typeof (self)weakSelf = self;
    pickview.clickIndexBlock = ^(NSInteger index) {
        weakSelf.valueLabel.text = weakSelf.selectedNameArray[index];
        [weakSelf getListDataForIndex:weakSelf.selectedIdArray[index] tag:index];
    };
    [WINDOW addSubview:pickview];
}

#pragma mark -- 选择时间
-(void)clickSelectedDateButton:(UIButton *)sender
{
    XLsn0wPickerTimer *pickerDate = [[XLsn0wPickerTimer alloc] init];
//    pickerDate.yearLeast = 2019;
    pickerDate.xlsn0wDelegate = self;
    [pickerDate show];
}

- (void)pickerTimer:(XLsn0wPickerTimer *)pickerTimer year:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    
    NSString *selectD = [NSString stringWithFormat:@"%ld%02ld%02ld", (long)year, (long)month, (long)day];
    if ([selectD integerValue]<[[NSString getCurrentTimesAndFormat:@"YYYYMMdd"] integerValue]) {
        [[ADShowMessage shareShowMessage]showTextOnly:@"限办时间不能小于当前时间" showInView:self.view];
        return;
    }
    
    NSString *text = [NSString stringWithFormat:@"%ld-%02ld-%02ld", (long)year, (long)month, (long)day];
    [self.selectedDateButton setTitle:[NSString stringWithFormat:@"限办时间：%@",text] forState:UIControlStateNormal];
    
    self.dateStr = [NSString stringWithFormat:@"%ld/%02ld/%02ld", (long)year, (long)month, (long)day];
    
}


#pragma mark -- UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MONoticeSendViewCell *cell = [MONoticeSendViewCell cellWithTableView:tableView andIndexPath:indexPath];
    MONoticeSendModel *model = self.dataSource[indexPath.row];
    
    cell.model = model;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [MONoticeSendViewCell heightForMONoticeSendViewCellAndModel:self.dataSource[indexPath.row]];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0001;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    return nil;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MONoticeSendModel *model = self.dataSource[indexPath.row];
    if ([model.selectedTypeStr integerValue]==0) {
        model.selectedTypeStr = @"1";
    }else{
        model.selectedTypeStr = @"0";
    }
    [self.tableView reloadData];
}

#pragma mark - 设置顶头分割线
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        if (@available(iOS 8.0, *)) {
            [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        if (@available(iOS 8.0, *)) {
            [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}

#pragma mark -懒加载
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-StatusBarAndNavigationBarHeight - kHConversions(49)) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = KGrayColor_F3F3F3;
        _tableView.separatorColor = KGrayColor_F3F3F3;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

-(UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        _headerView.backgroundColor = KGrayColor_F3F3F3;
        
        UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 1)];
        backView.backgroundColor = [UIColor whiteColor];
        [_headerView addSubview:backView];
        
        CGFloat buttonHeight = kHConversions(54);
        CGFloat Y1 = 0;
        if (self.titleStr.length==0) {
            self.titleStr = @"";
        }
        //
        self.dateStr = [NSString getCurrentTimesAndFormat:@"YYYY/MM/dd"];
        NSArray *arr = @[[NSString stringWithFormat:@"标题：%@",self.titleStr],[NSString stringWithFormat:@"%@%@",@"限办时间：",[NSString getCurrentTimesAndFormat:@"YYYY-MM-dd"]]];
        for (int i = 0; i<2; i++) {
            UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(kWConversions(20),(buttonHeight+1)*i , SCREEN_WIDTH - kWConversions(20) * 2, kHConversions(54))];
            if (i==1) {
                [button addTarget:self action:@selector(clickSelectedDateButton:) forControlEvents:UIControlEventTouchUpInside];
                self.selectedDateButton = button;
            }
            [button setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentLeft)];
            [button setTitleColor:KBlackColor_2A2A2A forState:UIControlStateNormal];
            [button setTitle:arr[i] forState:UIControlStateNormal];
            button.titleLabel.font = FONT_SIZE(15);
            [backView addSubview:button];
            
            UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, button.bottom, SCREEN_WIDTH, 1)];
            lineView.backgroundColor = KGrayColor_F3F3F3;
            [backView addSubview:lineView];
            Y1 = lineView.bottom;
        }
        
        UILabel *addDescLabel = [[UILabel alloc]initWithFrame:CGRectMake(kWConversions(20), Y1 + kHConversions(19), SCREEN_WIDTH - kWConversions(20)*2, 16)];
        addDescLabel.text = @"附加信息";
        addDescLabel.font = FONT_SIZE(15);
        addDescLabel.textColor = KBlackColor_2A2A2A;
        [backView addSubview:addDescLabel];
        
        self.textView = [[SNTextView alloc]initWithFrame:CGRectMake(kWConversions(15), addDescLabel.bottom + kHConversions(12),(int)(SCREEN_WIDTH - kWConversions(15)*2), (int)kHConversions(100))];
        self.textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.textView.backgroundColor = [UIColor whiteColor];
        self.textView.placeholder = @"请输入附加信息";
        self.textView.placeholderColor = KGrayColor_BABEC2;
        self.textView.font = FONT_SIZE(12);
        self.textView.textColor = KBlackColor_2A2A2A;
        [backView addSubview:self.textView];
        
        backView.height = self.textView.bottom + kHConversions(19);
        
        UIButton *sendButton = [[UIButton alloc]initWithFrame:CGRectMake(0, backView.bottom + 10, SCREEN_WIDTH, kHConversions(54))];
        sendButton.backgroundColor = KWhiteColor;
        [sendButton addTarget:self action:@selector(clickSendSelectedButton:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:sendButton];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(kWConversions(20), 0, 100, kHConversions(54))];
        label.text = @"送领导审核";
        label.font = FONT_SIZE(15);
        label.textColor = KBlackColor_2A2A2A;
        [sendButton addSubview:label];
        
        CGFloat VALUELABELWIDTH = SCREEN_WIDTH - kWConversions(20)*2-kWConversions(15) - label.width - kWConversions(15);
        self.valueLabel = [[UILabel alloc]initWithFrame:CGRectMake(label.right + kWConversions(15), 0, VALUELABELWIDTH, kHConversions(54))];
        self.valueLabel.textColor = KGrayColor_919395;
        self.valueLabel.font = FONT_SIZE(15);
        self.valueLabel.textAlignment = NSTextAlignmentRight;
        self.valueLabel.text = @"请选择";
        [sendButton addSubview:self.valueLabel];
        
        UIButton *rightImageView = [[UIButton alloc]initWithFrame:CGRectMake(self.valueLabel.right, 0, kWConversions(15), kHConversions(54))];
        [rightImageView setImage:IMAGE(@"right_notice") forState:UIControlStateNormal];
        [rightImageView setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentRight)];
        rightImageView.userInteractionEnabled = NO;
        [sendButton addSubview:rightImageView];
        
        _headerView.height = sendButton.bottom;
    }
    return _headerView;
}


-(UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, self.tableView.bottom, SCREEN_WIDTH, kHConversions(49))];
        _bottomView.backgroundColor = [UIColor whiteColor];
        
        CGFloat buttonW = (SCREEN_WIDTH - 1)/2;
        NSArray *arr = @[@"发送",@"取消"];
        for (int i = 0; i<2; i++) {
            UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake((buttonW+1)*i, 0, buttonW, kHConversions(49))];
            button.tag = i;
            [button addTarget:self action:@selector(clickSendOrCancelButton:) forControlEvents:UIControlEventTouchUpInside];
            [button setTitle:arr[i] forState:UIControlStateNormal];
            button.titleLabel.font = FONT_SIZE(13);
            if (i==0) {
                [button setTitleColor:KBlueColor_2C94FF forState:UIControlStateNormal];
            }else{
                [button setTitleColor:KBlackColor_2A2A2A forState:UIControlStateNormal];
            }
            [_bottomView addSubview:button];
            
            if (i==0) {
                UIView *line = [[UIView alloc]initWithFrame:CGRectMake(button.right, 0, 1, kHConversions(26))];
                line.backgroundColor = KGrayColor_ededed;
                line.centerY = kHConversions(49)/2;
                [_bottomView addSubview:line];
            }
        }
        
    }
    return _bottomView;
}


@end
